import 'bytemd/dist/index.css';
// 解析元数据
import frontmatter from '@bytemd/plugin-frontmatter';
// 解析gemoji表情
import gemoji from '@bytemd/plugin-gemoji';
// 支持GFM(自动链接文字、删除、表格、任务列表)
import gfm from '@bytemd/plugin-gfm';
// 代码高亮
import highlight from '@bytemd/plugin-highlight';
// 支持数学公式
import math from '@bytemd/plugin-math';
import { Editor, Viewer } from '@bytemd/react';
// 设置编辑器为简体中文
import gfmZhHans from '@bytemd/plugin-gfm/locales/zh_Hans.json';
import zhHans from 'bytemd/locales/zh_Hans.json';
// juejin样式
import './index.scss';
import './juejin.scss';
// 代码块行号插件
import { codeLinesPlugin } from '@/plugins/codeLines';

import { uploadFile } from '@/services/fileManage';
import { message } from 'antd';
import type { BytemdPlugin } from 'bytemd';
import { useEffect, useState } from 'react';
const plugins: BytemdPlugin[] = [
  gfm({ locale: gfmZhHans }),
  highlight(),
  gemoji(),
  frontmatter(),
  codeLinesPlugin(),
  math({
    locale: {
      inline: '行内公式',
      block: '块级公式',
    },
  }),
];

type Props = {
  onlyRead?: boolean;
  defaultValue?: string;
  onChange?: (e: string) => void;
};

// 上传图片
async function uploadImages(files: File[]) {
  let imgUrl = '';
  let formData = new FormData();
  formData.append('file', files[0]);
  const res = await uploadFile(formData);
  message.success(res.msg);
  return [
    {
      url: res.data.img_url,
      alt: res.data.fileName,
    },
  ];
}

const MdEditer: React.FC<Props> = ({ onlyRead, defaultValue, onChange }) => {
  const [value, setValue] = useState(() => defaultValue || '');
  useEffect(() => {
    setValue(defaultValue || '');
  }, [defaultValue]);
  const onValueChange = (e: string) => {
    setValue(e);
    onChange && onChange(e);
  };

  return (
    <>
      {onlyRead ? (
        <Viewer plugins={plugins} value={value} />
      ) : (
        <Editor
          locale={zhHans}
          plugins={plugins}
          value={value}
          onChange={onValueChange}
          uploadImages={uploadImages}
        />
      )}
    </>
  );
};

export default MdEditer;
